package org.lanyu.springainovel.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.novel.entity.BookSetting;
import org.lanyu.springainovel.novel.mapper.BookSettingMapper;
import org.lanyu.springainovel.novel.service.BookSettingService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 小说其他设定服务实现类
 */
@Slf4j
@Service
public class BookSettingServiceImpl extends ServiceImpl<BookSettingMapper, BookSetting> implements BookSettingService {

    @Override
    public List<BookSetting> getSettingsByBookId(Long bookId) {
        QueryWrapper<BookSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id", bookId);
        queryWrapper.orderByDesc("update_time");
        
        return this.list(queryWrapper);
    }

    @Override
    public List<BookSetting> addSetting(Long bookId, BookSetting setting) {
        // 创建新实体
        BookSetting entity = new BookSetting();
        BeanUtils.copyProperties(setting, entity);
        entity.setBookId(bookId);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        this.save(entity);
        
        // 返回更新后的设定列表
        return getSettingsByBookId(bookId);
    }

    @Override
    public BookSetting updateSetting(Long id, BookSetting setting) {
        // 获取现有设定
        BookSetting existingSetting = this.getById(id);
        if (existingSetting == null) {
            throw new RuntimeException("未找到ID为 " + id + " 的设定");
        }
        
        // 更新设定
        BeanUtils.copyProperties(setting, existingSetting, "id", "bookId", "createTime");
        existingSetting.setUpdateTime(LocalDateTime.now());
        
        // 保存更新
        this.updateById(existingSetting);
        
        return existingSetting;
    }

    @Override
    public boolean deleteSetting(Long id) {
        // 检查设定是否存在
        BookSetting existingSetting = this.getById(id);
        if (existingSetting == null) {
            throw new RuntimeException("未找到ID为 " + id + " 的设定");
        }
        
        // 删除设定
        return this.removeById(id);
    }

    @Override
    public BookSetting getSettingById(Long id) {
        return this.getById(id);
    }
}